<template>
  <div class="dg-uplod-file" :class="{'disabled': disabled}">
    <el-upload
      :id="uploadId"
      :list-type="listType"
      :drag="drag"
      :action="action"
      :limit="limit"
      :multiple="multiple"
      :auto-upload="autoUpload"
      :on-change="handChange"
      :headers="headers"
      :accept="accept"
      :file-list="showFileList"
      :disabled="disabled"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-success="onSuccess"
      :on-error="onError"
      @clearFiles="clearFiles"
      @abort="abort"
      @submit="submit"
      ref="upload"
    >
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </template>
      <template v-else>
        <el-button size="small" type="primary" :disabled="disabled">点击上传</el-button>
      </template>
      <div class="el-upload__tip" slot="tip">{{tip}}</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  // name: "file-upload",
  props: {
    listType: {
      type: String,
      default: "text"
    },
     // 服务器 文件显示服务器
    domain: {
      type: String,
      default: ''
    },
    
    drag: {
      type: Boolean,
      default: false
    },
    // 请求头头部
    headers: {
      type: Object,
      default: () => {}
    },
    value: {
      type: Array,
      default: () => []
    },
    // 上传文件类型
    accept: {
      type: String,
      default: ""
    },

    // 必选参数，上传的地址
    action: {
      type: String,
      // required: true
      default: ""
    },
    limit: {
      type: Number,
      default: 9
    },
    // 是否支持多选文件
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否在选取文件后立即进行上传
    autoUpload: {
      type: Boolean,
      default: true
    },
    token: {
      type: String,
      default: ""
    },
    tip: {
      type: String,
      default: ""
    },
    width: {
      type: Number,
      default: 100
    },
    height: {
      type: Number,
      default: 100
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: true
    },
    responseUrlField: {
      type: String,
      default: 'data'
    }
  },
  data() {
    return {
      uploadId: "",
      uploadBoxHTMLDOM: null,
      // fileList: this.value.map(item => {
      //   return {
      //     // key: item.key ? item.key : (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999),
      //     uid: item.uid,
      //     name: item.name,
      //     // status: item.status ? item.status : 'success'
      //     url: item.url
      //   };
      // })
      fileList: this.value
    };
  },
  mounted() {
    if (this.drag) {
      this.uploadId = "upload_" + parseInt(Math.random() * 1000);
      this.$nextTick(() => {
        this.uploadBoxHTMLDOM = document.querySelector('#' +  this.uploadId + " .el-upload");
        this.resUploadSize();
      })
    }
  },
  computed: {
    showFileList() {
      if (this.autoUpload) {
        let s = []
        this.fileList.map(item => {
          s.push({
            ...item,
            url: this.domain + item.url
          })
        })
        return s
      } else {
        return this.fileList
      }
    }
  },
  watch: {
    fileList: {
      deep: true,
      handler(val) {
        this.$emit('input', this.fileList)
      }
    },
    height() {
      this.resUploadSize();
    },
    width() {
      this.resUploadSize();
    }
  },
  methods: {
    resUploadSize() {
      if (this.uploadBoxHTMLDOM) {
        this.uploadBoxHTMLDOM.style.width = this.width + "px";
        this.uploadBoxHTMLDOM.style.height = this.height + "px";
      }

    },
    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     */
    handChange(file, fileList) {
      this.$emit("fileUpload", {
          type: "onChange",
          data: {
            file,
            fileList
          }
        });
      if (!this.autoUpload) {
        this.fileList = fileList
      }
    },

    // 点击文件列表中已上传的文件时的钩子
    onPreview(file) {
      this.$emit("fileUpload", {
        type: "onPreview",
        data: {
          file
        }
      });
    },

    // 	文件列表移除文件时的钩子
    onRemove(file, fileList) {
      this.fileList.splice(this.fileList.findIndex(item => item.uid === file.uid), 1)
      this.$emit("fileUpload", {
        type: "onRemove",
        data: {
          file,
          fileList
        }
      });
    },

    $t(obj, key) {
      if (typeof obj !== 'object') {
        return null
      }
        let arr = key.split('.')
        let s = obj
        for(let i = 0; i < arr.length; i++) {
            s = s[arr[i]]
        }
        return s
    },
    // 文件上传成功时的钩子
    onSuccess(response, file, fileList) {
      let newFile = {
        uid: file.uid,
        name: file.name,
        size: file.size,
        percentage: file.percentage,
        url: this.$t(response, this.responseUrlField)
      }

      this.fileList.push(newFile)
      sessionStorage.setItem(
        "test_fileupload_success",
        JSON.stringify(fileList)
      );
      this.$emit("fileUpload", {
        type: "onSuccess",
        data: {
          response,
          file,
          fileList
        }
      });
    },

    // 文件上传失败的函数
    onError(error, file, fileList) {
      this.$emit("fileUpload", {
        type: "onError",
        data: {
          error,
          file,
          fileList
        }
      });
    },

    // 清空已上传的文件列表（该方法不支持在 before-upload 中调用
    clearFiles() {
      this.fileList = []
      this.$emit("fileUpload", {
        type: "clearFiles",
        data: arguments
      });
    },

    // abort 取消上传请求
    abort(e) {
      console.log("abort e: ", e);
    },

    // 手动上传文件列表
    submit(e) {
      console.log("submit e: ", e);
    }
  }
};
</script>

<style lang="scss">
.dg-uplod-file {
  .el-upload {
    height: 100%;
    .el-upload-dragger {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding: 4px 6px;
      height: 100%;
      width: 100% !important;
      box-sizing: border-box;
      .el-icon-upload {
        width: 100%;
        margin: 0 auto;
        font-size: 36px;
      }
    }
  }

  &.disabled {
    .el-upload--picture-card,
    .el-upload-dragger,
    .el-upload {
      cursor: no-drop;
    }
  }
}
</style>


